package com.jintu.portal.utils;

import com.alibaba.fastjson.JSONArray;
import com.jintu.portal.config.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.Set;

/**
 * @author very
 */
@Slf4j
public class CommonUtil {

    public static String genMongoId(String orderId, Integer userId) {
        String src = orderId + userId;
        return DigestUtils.md5Hex(src);
    }

    public static String getDataSourceRedisKey(String orderId, Integer userId) {
        return Constant.DATA_SOURCE_PREFIX_KEY + userId + "_" + orderId;
    }

    public static String getScoreCardRedisKey(String orderId, Integer userId){
        return Constant.SCORE_CARD_PREFIX_KEY + userId + "_" + orderId;
    }

    public static String getRuleChainRedisKey(String orderId, Integer userId){
        return Constant.RULE_CHAIN_PREFIX_KEY + userId + "_" + orderId;
    }

    public static JSONArray scoreCardString2Set(String str) {
        JSONArray scoreCards = new JSONArray();
        if (StringUtils.isNotBlank(str)) {
            try {
                String[] splits = str.split("\\" + Constant.SCORE_CARD_CODE_SPLIT);
                scoreCards.addAll(Arrays.asList(splits));
            } catch (Exception e) {
                log.error("解析可用评分卡字符串报错");
                log.error(e.getMessage(), e);
            }
        }
        return scoreCards;
    }

    public static String scoreCardSet2String(Set<String> scoreCards) {
        if (scoreCards == null || scoreCards.isEmpty()) {
            return "";
        }
        String str = "";
        for (String scoreCardCode : scoreCards) {
            if (StringUtils.isBlank(str)) {
                str += scoreCardCode;
            } else {
                str += Constant.SCORE_CARD_CODE_SPLIT + scoreCardCode;
            }
        }
        return str;
    }
}
